package org.tuoren.official.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.tuoren.common.core.utils.MapstructUtils;
import org.tuoren.common.mybatis.core.page.TableDataInfo;
import org.tuoren.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.tuoren.official.constant.ConstantUtils;
import org.tuoren.official.domain.Department;
import org.tuoren.official.domain.ProductLine;
import org.tuoren.official.domain.bo.ProductBo;
import org.tuoren.official.domain.vo.ProductImportVo;
import org.tuoren.official.domain.vo.ProductVo;
import org.tuoren.official.domain.Product;
import org.tuoren.official.es.domain.ProductEs;
import org.tuoren.official.es.esmapper.EsProductMapper;
import org.tuoren.official.mapper.DepartmentMapper;
import org.tuoren.official.mapper.ProductLineMapper;
import org.tuoren.official.mapper.ProductMapper;
import org.tuoren.official.service.IOssService;
import org.tuoren.official.service.IProductService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 产品信息Service业务层处理
 *
 * @author wl
 * @date 2024-11-26
 */
@RequiredArgsConstructor
@Service
public class ProductServiceImpl implements IProductService {

    private final ProductMapper baseMapper;
    private final ProductLineMapper lineMapper;
    private final EsProductMapper esMapper;
    private final IOssService ossService;
    private final DepartmentMapper departmentMapper;
    @Value("${oss.key.image}")
    String ossImageKey;

    /**
     * 查询产品信息
     *
     * @param id 主键
     * @return 产品信息
     */
    @Override
    public ProductVo queryById(Long id) {
        ProductVo productVo = baseMapper.selectVoById(id);
        if (productVo != null && StringUtils.isNotBlank(productVo.getDepartmentId())) {
            String[] departmentIds = productVo.getDepartmentId().split(ConstantUtils.SEPARATOR_DB);
            List<Long> departmentIdList = new ArrayList<>();
            String departmentName = "";
            for (String departmentId : departmentIds) {
                try {
                    Department department = departmentMapper.selectById(Long.valueOf(departmentId));
                    if (department != null) {
                        departmentIdList.add(Long.parseLong(departmentId.trim()));
                        departmentName += department.getName() + ConstantUtils.SEPARATOR;
                    }
                } catch (NumberFormatException e) {
                    // 处理异常情况，如日志记录或忽略无效的typeId
                    // 可以根据业务需求选择处理方式
                }
            }
            productVo.setDepartmentList(departmentIdList);
            productVo.setDepartmentName(departmentName==""?"":departmentName.substring(0, departmentName.length() - 1)+"。");
        }
        return productVo;
    }

    /**
     * 分页查询产品信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 产品信息分页列表
     */
    @Override
    public TableDataInfo<ProductVo> queryPageList(ProductBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Product> lqw = buildQueryWrapper(bo);
        Page<ProductVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        //将result的type_id字段转换为type_name字段,同样以逗号分隔
        result.getRecords().forEach(item -> {
            item.setTypeName(lineMapper.selectVoById(item.getTypeId()).getName());
            String departmentId = item.getDepartmentId();
            if (departmentId != null) {
                String[] departmentIds = departmentId.split(ConstantUtils.SEPARATOR_DB);
                String departmentName = "";
                for (String id : departmentIds) {
                    Department department = departmentMapper.selectById(Long.valueOf(id));
                    if (department != null) {
                        departmentName += department.getName() + ConstantUtils.SEPARATOR;
                    }
                }
                item.setDepartmentName(departmentName==""?"":departmentName.substring(0, departmentName.length() - 1));
            }
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的产品信息列表
     *
     * @param bo 查询条件
     * @return 产品信息列表
     */
    @Override
    public List<ProductVo> queryList(ProductBo bo) {
        LambdaQueryWrapper<Product> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Product> buildQueryWrapper(ProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Product> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), Product::getName, bo.getName());
        lqw.eq(bo.getTypeId() != null, Product::getTypeId, bo.getTypeId());
        lqw.eq(StringUtils.isNotBlank(bo.getSummary()), Product::getSummary, bo.getSummary());
        lqw.like(StringUtils.isNotBlank(bo.getSpec()), Product::getSpec, bo.getSpec());
        lqw.like(StringUtils.isNotBlank(bo.getModel()), Product::getModel, bo.getModel());
        lqw.eq(StringUtils.isNotBlank(bo.getDescribes()), Product::getDescribes, bo.getDescribes());
        lqw.eq(StringUtils.isNotBlank(bo.getPhotoUrl()), Product::getPhotoUrl, bo.getPhotoUrl());
        if (StringUtils.isNotBlank(bo.getDepartmentId())) {
            lqw.apply("find_in_set ('" + bo.getDepartmentId() + "',department_id)");
        }
        lqw.orderByAsc(Product::getOrderNum);
        return lqw;
    }

    /**
     * 新增产品信息
     *
     * @param bo 产品信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ProductBo bo) {
        Product add = MapstructUtils.convert(bo, Product.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            ProductEs bean = BeanUtil.toBean(add, ProductEs.class);
            esMapper.insert(bean);
        }
        return flag;
    }

    /**
     * 修改产品信息
     *
     * @param bo 产品信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ProductBo bo) {
        Product update = MapstructUtils.convert(bo, Product.class);
        validEntityBeforeSave(update);
        boolean b = baseMapper.updateById(update) > 0;
        if (b) {
            ProductEs bean = BeanUtil.toBean(update, ProductEs.class);
            esMapper.updateById(bean);
        }
        return b;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Product entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除产品信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        Boolean b = baseMapper.deleteByIds(ids) > 0;
        if (b) {
            for (Long id : ids) {
                esMapper.deleteById(id);
            }
        }
        return b;
    }

    @Override
    public void importData(List<ProductImportVo> result) {
        //将result的typename都换为id
        result.forEach(productImportVo -> productImportVo.setTypeId(lineMapper.selectOne(Wrappers.lambdaQuery(ProductLine.class).eq(ProductLine::getName, productImportVo.getTypeName().trim())).getId()));
        for (ProductImportVo productImportVo : result) {
            Product productBo = BeanUtil.toBean(productImportVo, Product.class);
            int insert = baseMapper.insert(productBo);
            ProductEs productEs = BeanUtil.toBean(productBo, ProductEs.class);
            esMapper.insert(productEs);
        }
    }
}
